<template>
  <div class="room-management-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="header-info">
          <h1 class="page-title">
            <svg class="title-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <rect x="3" y="4" width="18" height="18" rx="2" ry="2"/>
              <line x1="16" y1="2" x2="16" y2="6"/>
              <line x1="8" y1="2" x2="8" y2="6"/>
              <line x1="3" y1="10" x2="21" y2="10"/>
            </svg>
            房间管理
          </h1>
          <p class="page-description">管理和维护房间信息，包括房间状态、租赁情况等</p>
        </div>
        <div class="header-stats">
          <div class="stat-item">
            <div class="stat-icon available">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <path d="M9 12l2 2 4-4"/>
                <circle cx="12" cy="12" r="10"/>
              </svg>
            </div>
            <div class="stat-content">
              <span class="stat-number">--</span>
              <span class="stat-label">可用房间</span>
            </div>
          </div>
          <div class="stat-item">
            <div class="stat-icon occupied">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/>
                <circle cx="12" cy="7" r="4"/>
              </svg>
            </div>
            <div class="stat-content">
              <span class="stat-number">--</span>
              <span class="stat-label">已入住</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 数据表格 -->
    <div class="table-container">
      <el-card class="table-card" shadow="never">
        <ProTable
          ref="proTable"
          :dataCallback="dataCallback"
          :columns="columns"
          :requestApi="getRoomList"
          :initParam="initParam"
          :stripe="true"
        >
          <template #tableHeader>
            <div class="table-header">
              <div class="header-left">
                <h3 class="table-title">房间列表</h3>
                <span class="table-subtitle">管理所有房间信息和状态</span>
              </div>
              <div class="header-actions">
                <el-button type="primary" icon="Plus" @click="addHandle" class="add-btn">
                  新增房间
                </el-button>
              </div>
            </div>
          </template>
          <!-- 表格操作 -->
          <template #operation="scope">
            <div class="operation-buttons">
              <el-button type="success" icon="Edit" @click="editHandle(scope.row)" size="small" class="action-btn">
                修改
              </el-button>
              <el-button type="danger" icon="Delete" @click="deleteHandle(scope.row)" size="small" class="action-btn">
                删除
              </el-button>
            </div>
          </template>
        </ProTable>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="tsx">
import { onMounted, reactive, ref } from 'vue'
import { ColumnProps } from '@/components/ProTable/src/types'
import ProTable from '@/components/ProTable/src/ProTable.vue'
import { useRouter } from 'vue-router'
import { useHandleData } from '@/hooks/useHandleData'
import {
  deleteRoomById,
  getApartmentListByDistrictId,
  getCityList,
  getDistrictList,
  getProvinceList,
  getRoomList,
  updateRoomReleaseStatus,
} from '@/api/apartmentManagement'
import {
  ApartmentInterface,
  RegionInterface,
  RoomInterface,
} from '@/api/apartmentManagement/types'
import {
  getLabelByValue,
  RoomCheckInStatus,
  RoomCheckInStatusMap,
  RoomReleaseStatus,
} from '@/enums/constEnums'

const router = useRouter()

// *获取 ProTable 元素，调用其获取刷新数据方法
const proTable = ref<InstanceType<typeof ProTable>>()
// 地区数据
const areaInfo = reactive({
  // 省份数据
  provinceList: [] as RegionInterface[],
  provinceId: '',
  // 市区数据
  cityList: [] as RegionInterface[],
  cityId: '',
  // 区县数据
  districtList: [] as RegionInterface[],
  districtId: '',
  // 公寓数据
  apartmentList: [] as ApartmentInterface[],
  apartmentId: '',
})
// *表格配置项
const columns: ColumnProps[] = [
  {
    prop: 'provinceId',
    label: '省份',
    isShow: false,
    fieldNames: { label: 'name', value: 'id' },
    search: {
      el: 'select',
      render: () => {
        return (
          <el-select
            v-model={areaInfo.provinceId}
            placeholder="请选择省份"
            clearable
            key="provinceId"
            onChange={provinceChangeCallback}
            onClear={provinceClearCallback}
          >
            {areaInfo.provinceList.map((item) => (
              <el-option
                key={item.id}
                label={item.name}
                value={item.id}
              ></el-option>
            ))}
          </el-select>
        )
      },
    },
  },
  {
    prop: 'cityId',
    label: '城市',
    isShow: false,
    fieldNames: { label: 'name', value: 'id' },
    search: {
      el: 'select',
      key: 'cityId',
      render: () => {
        return (
          <el-select
            v-model={areaInfo.cityId}
            placeholder="请选择城市"
            clearable
            key="cityId"
            onChange={cityChangeCallback}
            onClear={cityClearCallback}
          >
            {areaInfo.cityList.map((item) => (
              <el-option
                key={item.id}
                label={item.name}
                value={item.id}
              ></el-option>
            ))}
          </el-select>
        )
      },
    },
  },
  {
    prop: 'districtId',
    label: '区域',
    isShow: false,
    fieldNames: { label: 'name', value: 'id' },
    search: {
      el: 'select',
      key: 'districtId',
      render: () => {
        return (
          <el-select
            v-model={areaInfo.districtId}
            placeholder="请选择区域"
            clearable
            onChange={districtChangeCallback}
            onClear={districtClearCallback}
          >
            {areaInfo.districtList.map((item) => (
              <el-option
                key={item.id}
                label={item.name}
                value={item.id}
              ></el-option>
            ))}
          </el-select>
        )
      },
    },
  },
  {
    prop: 'apartmentId',
    label: '公寓',
    isShow: false,
    fieldNames: { label: 'name', value: 'id' },
    search: {
      el: 'select',
      key: 'apartmentId',
      render: () => {
        return (
          <el-select
            v-model={areaInfo.apartmentId}
            placeholder="请选择公寓"
            clearable
            onChange={apartmentChangeCallback}
            onClear={apartmentClearCallback}
          >
            {areaInfo.apartmentList.map((item) => (
              <el-option
                key={item.id}
                label={item.name}
                value={item.id}
              ></el-option>
            ))}
          </el-select>
        )
      },
    },
  },
  { prop: 'roomNumber', label: '房间号' },
  { prop: 'rent', label: '租金（元/月）' },
  { prop: 'apartmentInfo.provinceName', label: '所处省份' },
  { prop: 'apartmentInfo.cityName', label: '所处城市' },
  { prop: 'apartmentInfo.districtName', label: '所处区域' },
  { prop: 'apartmentInfo.name', label: '所处公寓' },
  {
    prop: 'isCheckIn',
    label: '入住状态',
    render: ({ row }: { row: RoomInterface }) => {
      return row.isCheckIn === RoomCheckInStatus.NOT_CHECK_IN ? (
        <el-tag type="info">
          {getLabelByValue(RoomCheckInStatusMap, row.isCheckIn)}
        </el-tag>
      ) : (
        <el-tag type="success">
          {getLabelByValue(RoomCheckInStatusMap, row.isCheckIn)}
        </el-tag>
      )
    },
  },
  {
    prop: 'isRelease',
    label: '发布状态',
    render: ({ row }: { row: RoomInterface }) => {
      return (
        <el-switch
          active-value={RoomReleaseStatus.RELEASED}
          inactive-value={RoomReleaseStatus.NOT_RELEASED}
          v-model={row.isRelease}
          onChange={() =>
            updateRoomReleaseStatus(row.id, row.isRelease as RoomReleaseStatus)
          }
        ></el-switch>
      )
    },
  },
  { prop: 'operation', label: '操作', fixed: 'right', width: 230 },
]

// *查询参数
const initParam = reactive({})

//#region <省市区查询相关>
// 获取省份
async function getProvinceListHandle() {
  try {
    const { data } = await getProvinceList()
    areaInfo.provinceList = data
    proTable.value?.enumMap.set('provinceId', areaInfo.provinceList)
  } catch (error) {
    console.log(error)
  }
}
// 获取城市
async function getCityListHandle(provinceId: number) {
  try {
    const { data } = await getCityList(provinceId)
    areaInfo.cityList = data
    proTable.value?.enumMap.set('cityId', areaInfo.cityList)
  } catch (error) {
    console.log(error)
  }
}
// 获取区域
async function getDistrictListHandle(cityId: number) {
  try {
    const { data } = await getDistrictList(cityId)
    areaInfo.districtList = data
    proTable.value?.enumMap.set('districtId', areaInfo.districtList)
  } catch (error) {
    console.log(error)
  }
}
// 获取公寓
async function getApartmentListHandle(districtId: number) {
  try {
    const { data } = await getApartmentListByDistrictId(districtId)
    areaInfo.apartmentList = data
    proTable.value?.enumMap.set('apartmentId', areaInfo.apartmentList)
  } catch (error) {
    console.log(error)
  }
}
// 重置市数据
function resetCity() {
  areaInfo.cityId = ''
  areaInfo.cityList = []
  proTable.value?.enumMap.set('cityId', [])
  proTable.value!.searchParam.cityId = ''
}
// 重置区数据
function resetDistrict() {
  areaInfo.districtId = ''
  areaInfo.districtList = []
  proTable.value?.enumMap.set('districtId', [])
  proTable.value!.searchParam.districtId = ''
}
// 重置公寓数据
function resetApartment() {
  areaInfo.apartmentId = ''
  areaInfo.apartmentList = []
  proTable.value?.enumMap.set('apartmentId', [])
  proTable.value!.searchParam.apartmentId = ''
}
// 省份改变回调
const provinceChangeCallback = async () => {
  let provinceId = proTable.value!.searchParam.provinceId
  if (provinceId) {
    resetCity()
    resetDistrict()
    resetApartment()
    await getCityListHandle(provinceId)
  }
}
// 省份清除回调
const provinceClearCallback = () => {
  areaInfo.provinceId = ''
  proTable.value!.searchParam.provinceId = ''
  resetCity()
  resetDistrict()
  resetApartment()
}
// 城市改变回调
const cityChangeCallback = async () => {
  let cityId = proTable.value!.searchParam.cityId
  if (cityId) {
    resetDistrict()
    resetApartment()
    await getDistrictListHandle(cityId)
  }
}
// 城市清除回调
const cityClearCallback = () => {
  console.log('清空城市')
  areaInfo.cityId = ''
  proTable.value!.searchParam.cityId = ''
  resetDistrict()
  resetApartment()
}
// 区域改变回调
const districtChangeCallback = async () => {
  let districtId = proTable.value!.searchParam.districtId
  if (districtId) {
    resetApartment()
    await getApartmentListHandle(districtId)
  }
}
// 区域清除回调
const districtClearCallback = () => {
  console.log('清空区域')
  areaInfo.districtId = ''
  proTable.value!.searchParam.districtId = ''
  resetApartment()
}
// 公寓改变回调
const apartmentChangeCallback = async () => {
  console.log('公寓改变')
}
// 公寓清除回调
const apartmentClearCallback = () => {
  console.log('清空公寓')
  areaInfo.apartmentId = ''
  proTable.value!.searchParam.apartmentId = ''
}
//#endregion

// 处理返回的数据格式
const dataCallback = (data: any) => {
  return {
    list: data?.records,
    total: data?.total,
  }
}
// 查看
const editHandle = (row: RoomInterface) => {
  console.log(row)
  router.push({
    path: '/apartmentManagement/roomManagement/addOrEditRoom',
    query: {
      id: row.id,
    },
  })
}
// 新增
const addHandle = () => {
  router.push({
    path: '/apartmentManagement/roomManagement/addOrEditRoom',
  })
}
// 通过，不通过
const deleteHandle = async (row: RoomInterface) => {
  // status	0301-审核通过 0302-审核不通过
  await useHandleData(
    deleteRoomById,
    row.id,
    `删除${row.apartmentInfo.name + row.roomNumber}房间`,
  )
  // 修改row
  proTable.value?.getTableList()
}
onMounted(() => {
  // 获取省份
  getProvinceListHandle()
})
</script>

<style scoped lang="scss">
.room-management-container {
  padding: 1.5rem;
  background: var(--bg-color-page);
  min-height: 100vh;

  .page-header {
    margin-bottom: 2rem;
    padding: 2rem;
    background: linear-gradient(135deg, var(--secondary-gradient-start), var(--secondary-gradient-end));
    border-radius: 20px;
    color: white;

    .header-content {
      display: flex;
      align-items: center;
      justify-content: space-between;

      .header-info {
        flex: 1;

        .page-title {
          display: flex;
          align-items: center;
          font-size: 2rem;
          font-weight: 700;
          margin-bottom: 0.5rem;
          text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

          .title-icon {
            width: 2.5rem;
            height: 2.5rem;
            margin-right: 1rem;
          }
        }

        .page-description {
          font-size: 1rem;
          opacity: 0.9;
          margin: 0;
        }
      }

      .header-stats {
        display: flex;
        gap: 2rem;

        .stat-item {
          display: flex;
          align-items: center;
          padding: 1rem 1.5rem;
          background: rgba(255, 255, 255, 0.15);
          border-radius: 16px;
          backdrop-filter: blur(10px);

          .stat-icon {
            width: 50px;
            height: 50px;
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 1rem;

            &.available {
              background: rgba(67, 233, 123, 0.3);
              color: #43e97b;
            }

            &.occupied {
              background: rgba(245, 87, 108, 0.3);
              color: #f5576c;
            }

            svg {
              width: 24px;
              height: 24px;
            }
          }

          .stat-content {
            display: flex;
            flex-direction: column;

            .stat-number {
              font-size: 1.5rem;
              font-weight: 700;
              margin-bottom: 0.25rem;
            }

            .stat-label {
              font-size: 0.8rem;
              opacity: 0.8;
            }
          }
        }
      }
    }
  }

  .table-container {
    .table-card {
      border-radius: 16px;
      border: none;
      overflow: hidden;

      :deep(.el-card__body) {
        padding: 0;
      }

      .table-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 1.5rem 2rem;
        background: var(--bg-color-light);
        border-bottom: 1px solid var(--border-color-light);

        .header-left {
          .table-title {
            font-size: 1.3rem;
            font-weight: 600;
            color: var(--text-color-primary);
            margin: 0 0 0.25rem 0;
          }

          .table-subtitle {
            font-size: 0.9rem;
            color: var(--text-color-secondary);
          }
        }

        .header-actions {
          .add-btn {
            background: linear-gradient(135deg, #67c23a, #409eff);
            border: 2px solid rgba(255, 255, 255, 0.3);
            border-radius: 12px;
            padding: 0.75rem 1.5rem;
            font-weight: 600;
            font-size: 0.95rem;
            color: white;
            text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
            box-shadow: 0 4px 15px rgba(103, 194, 58, 0.3);
            transition: all 0.3s ease;

            &:hover {
              transform: translateY(-2px);
              box-shadow: 0 8px 25px rgba(103, 194, 58, 0.4);
              border-color: rgba(255, 255, 255, 0.5);
              background: linear-gradient(135deg, #85ce61, #66b1ff);
            }

            &:active {
              transform: translateY(0);
              box-shadow: 0 2px 8px rgba(103, 194, 58, 0.3);
            }

            .el-icon {
              margin-right: 0.5rem;
              font-size: 1rem;
            }
          }
        }
      }

      :deep(.pro-table) {
        .el-table {
          border-radius: 0;

          .el-table__header {
            th {
              background: var(--bg-color-light);
              color: var(--text-color-primary);
              font-weight: 600;
              border-bottom: 1px solid var(--border-color-light);
            }
          }

          .el-table__body {
            tr {
              &:hover {
                background: var(--bg-color-light);
              }

              td {
                border-bottom: 1px solid var(--border-color-light);
                color: var(--text-color-primary);
              }
            }
          }
        }

        .table-search {
          padding: 1.5rem 2rem;
          background: var(--bg-color-light);
          border-bottom: 1px solid var(--border-color-light);

          :deep(.el-form-item) {
            margin-bottom: 1rem;

            .el-form-item__label {
              color: var(--text-color-primary);
              font-weight: 500;
            }

            .el-input,
            .el-select {
              .el-input__wrapper {
                border-radius: 8px;
                border: 1px solid var(--border-color-light);
                transition: all 0.3s ease;

                &:hover {
                  border-color: var(--secondary-color);
                }

                &.is-focus {
                  border-color: var(--secondary-color);
                  box-shadow: 0 0 0 2px rgba(var(--secondary-color-rgb), 0.1);
                }
              }
            }
          }

          .search-operation {
            .el-button {
              border-radius: 8px;
              font-weight: 500;

              &.el-button--primary {
                background: var(--secondary-color);
                border-color: var(--secondary-color);
              }
            }
          }
        }
      }

      .operation-buttons {
        display: flex;
        gap: 0.5rem;

        .action-btn {
          border-radius: 8px;
          font-weight: 500;
          transition: all 0.3s ease;

          &:hover {
            transform: translateY(-1px);
          }

          &.el-button--success {
            background: linear-gradient(135deg, #67c23a, #85ce61);
            border: none;
          }

          &.el-button--danger {
            background: linear-gradient(135deg, #f56c6c, #f78989);
            border: none;
          }
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .room-management-container {
    padding: 1rem;

    .page-header {
      padding: 1.5rem;

      .header-content {
        flex-direction: column;
        text-align: center;

        .header-info {
          margin-bottom: 1.5rem;

          .page-title {
            justify-content: center;
            font-size: 1.5rem;

            .title-icon {
              width: 2rem;
              height: 2rem;
            }
          }
        }

        .header-stats {
          justify-content: center;
          flex-wrap: wrap;
          gap: 1rem;

          .stat-item {
            padding: 0.75rem 1rem;
          }
        }
      }
    }

    .table-container {
      .table-card {
        .table-header {
          flex-direction: column;
          gap: 1rem;
          text-align: center;
        }
      }
    }
  }
}
</style>
